/*            Copyright(c) 2006-2008 Dave Sexton           *
 * http://www.codeplex.com/DocProject                      *
 * http://www.codeplex.com/DocProject/Project/License.aspx *
 ***********************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using DaveSexton.DocProject.Sandcastle.Resources;

namespace DaveSexton.DocProject.Sandcastle.TopicManagement
{	
	public sealed class MRefBuilderConfigDocument : MarshalByRefObject
	{
		#region Public Properties
		public string ConfigurationFile
		{
			get
			{
				if (configurationFile == null)
					throw new InvalidOperationException(Errors.MRefBuilderConfigDocumentNotLoaded);

				return configurationFile;
			}
		}

		public MRefBuilderConfigApiFilter ApiFilter
		{
			get
			{
				if (apiFilter == null)
				{
					if (dduetools == null)
						throw new InvalidOperationException(Errors.MRefBuilderConfigDocumentNotLoaded);

					apiFilter = new MRefBuilderConfigApiFilter(dduetools);
				}

				return apiFilter;
			}
		}
		#endregion

		#region Private / Protected
		private readonly XmlDocument document = new XmlDocument();
		private XmlNode dduetools;
		private MRefBuilderConfigApiFilter apiFilter;
		private string configurationFile;
		#endregion

		#region Constructors
		/// <summary>
		/// Constructs a new instance of the <see cref="MRefBuilderConfigDocument" /> class.
		/// </summary>
		public MRefBuilderConfigDocument()
		{
		}
		#endregion

		#region Methods
		[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.LinkDemand,
			Flags = System.Security.Permissions.SecurityPermissionFlag.Infrastructure)]
		public override object InitializeLifetimeService()
		{
			return null;
		}

		public void Load(string configFile)
		{
			if (string.IsNullOrEmpty(configFile))
				throw new ArgumentException(Resources.Errors.NullOrEmpty, "configFile");

			this.configurationFile = configFile;

			apiFilter = null;

			document.Load(configFile);

			XmlNode configuration = document.SelectSingleNode("/configuration");

			if (configuration == null)
				throw new InvalidOperationException(Errors.MRefBuilderConfigMissingRoot);

			dduetools = configuration.SelectSingleNode("dduetools");

			if (dduetools == null)
				dduetools = configuration.AppendChild(document.CreateElement("dduetools"));
		}

		public void Save()
		{
			if (configurationFile == null)
				throw new InvalidOperationException(Errors.MRefBuilderConfigDocumentNotLoaded);

			document.Save(configurationFile);
		}
		#endregion
	}
}
